package com.ying.user.utils;

import cn.hutool.core.util.ObjectUtil;
import com.ying.user.entity.dto.MmUserDetails;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * Spring Security工具类
 */
public class SecurityUtils {

    // 匿名用户 用户名
    private static final String ANONYMOUS_NAME = "匿名用户";

    /**
     * 获取当前登录用户用户名
     *
     * @return 当前登录用户用户名
     */
    public static String getCurrentUsername() {
        MmUserDetails currentUser = getCurrentUser();
        return ObjectUtil.isNull(currentUser) ? ANONYMOUS_NAME : currentUser.getUsername();
    }

    /**
     * 获取当前登录用户信息
     *
     * @return 当前登录用户信息，匿名登录时，为null
     */
    public static MmUserDetails getCurrentUser() {
        Object userInfo = SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        if (userInfo instanceof UserDetails) {
            return (MmUserDetails) userInfo;
        }
        return null;
    }
}
